<script type="text/javascript" src="helper.js"></script>
<script type="text/javascript" src="prefs.js"></script>
<script type="text/javascript" src="expanders.js"></script>
<script type="text/javascript">
(function() {
    var Helper = AE.Helper,
        Expanders = AE.Expanders,
        PrefsHelper = AE.PrefsHelper;

    var expandTabs = {};

    // Load expand service providers
    Helper.makeRequest({
        url : "exproviders.js",
        callback : function(xhr) {
            if (xhr.readyState === 4) {
                Expanders.add(JSON.parse(xhr.responseText));
            }
        }
    });

    chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
        // first cancel the expand url request
        if (expandTabs[tabId + ""]) {
            try {
                expandTabs[tabId + ""].abort();
            } catch(e) { }
            delete expandTabs[tabId + ""];
        }

        var url = tab.url,
            shorterners = PrefsHelper.get("shorterners"),
            expander = PrefsHelper.get("expander");

        // check if the url is a shorted url
        var el = document.createElement("A");
        el.href = url;
        if (shorterners.indexOf(el.hostname.toLowerCase()) < 0) {
            return;
        }

        // send expand request
        expandTabs[tabId + ""] = Expanders.use(expander, url, function(orgiUrl) {
            delete expandTabs[tabId + ""];
            chrome.tabs.update(tabId, {
                url : orgiUrl
            });
        });
    });
})();
</script>
